<script setup lang="ts">
import { NButton, NIcon, NInput, NPopconfirm, NSwitch } from 'naive-ui'
import { SearchOutline } from '@vicons/ionicons5'
import { Reset } from '@vicons/carbon'
import { onMounted, type Ref, ref, reactive, type CSSProperties, h } from 'vue'
import { topicGetTopicListService, topicDeleteTopicService, topicChangeTopicService } from '@/api/topic'
import { DeleteOutlined } from '@vicons/antd'
import { formatTime } from '@/utils/format'
const message = useMessage()
//帖子数量
const count: Ref<number> = ref(0)
//是否在加载
const isLoading: Ref<boolean> = ref(false)
//获取帖子列表
const data: Ref<Api.Topic.TopicInfo[]> = ref([])
//帖子的类别
onMounted(async () => {
  isLoading.value = true
  const res = await topicGetTopicListService()
  count.value = res.data.data.length
  data.value = res.data.data
  //对数据的时间戳进行格式化
  data.value.forEach((item) => {
    item.create_time = formatTime(item.create_time)
  })
  isLoading.value = false
  console.log(res)
})

type RowData = {
  id: number
  t_uid: number
  t_title: string
  t_kind: string
  create_time: string
  t_content: string
  t_photo: string
  t_introduce: string
  recommend: boolean
}
//自定义按钮颜色
const railStyle = ({ focused, checked }: { focused: boolean; checked: boolean }) => {
  const style: CSSProperties = {}
  if (checked) {
    style.background = '#646CFF'
    if (focused) {
      style.boxShadow = '0 0 0 2px #646CFF'
    }
  }
  return style
}
//表格列
const createColumns = () => {
  return [
    {
      type: 'selection',
      fixed: 'left'
    },
    {
      title: 'ID',
      key: 'id',
      fixed: 'left',
      width: 100
    },
    {
      title: '作者id',
      key: 't_uid',
      fixed: 'left',
      width: 100
    },
    {
      title: '帖子名称',
      key: 't_title',
      fixed: 'left',
      width: 100
    },
    {
      title: '帖子类别',
      key: 't_kind',
      width: 100,
      render(row: RowData) {
        return h(NInput, {
          value: row.t_kind,
          onUpdateValue: (v) => {
            row.t_kind = v
          }
        })
      }
    },
    {
      title: '创建时间',
      key: 'create_time',
      width: 100
    },
    {
      title: '封面',
      key: 't_photo',
      width: 50,
      render(row: RowData) {
        return h('img', {
          src: row.t_photo,
          style: {
            width: '40px',
            height: '40px'
          }
        })
      }
    },
    {
      title: '简介',
      key: 't_introduce',
      width: 200
    },
    {
      title: '是否推荐',
      key: 'recommend',
      width: 100,
      render(row: RowData) {
        return h(
          NSwitch,
          {
            value: row.recommend,
            onClick: () => {
              row.recommend = !row.recommend
            },
            'rail-style': railStyle
          },
          { checked: () => '推荐', unchecked: () => '不推荐' }
        )
      }
    },
    {
      title: '操作',
      key: 'actions',
      fixed: 'right',
      width: 150,
      render: (row: RowData) => {
        return h(
          'div',
          {
            style: {
              display: 'flex',
              justifyContent: 'start',
              gap: '8px'
            }
          },
          {
            default: () => [
              h(
                NButton,
                { type: 'info', ghost: true, size: 'small', onClick: () => commit(row) },
                { default: () => '提交' }
              ),
              h(
                NPopconfirm,
                { positiveText: '确定', negativeText: '取消', onPositiveClick: () => handleDelete(row.id) },
                {
                  trigger: () => h(NButton, { type: 'error', ghost: true, size: 'small' }, { default: () => '删除' }),
                  default: () => '你确定要删除吗？'
                }
              )
            ]
          }
        )
      }
    }
  ]
}
const columns = createColumns()
// 分页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 30],
  onChange: (page: number) => {
    paginationReactive.page = page
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
  }
})
//搜索
type SearchForm = {
  t_uid: number | null
  t_title: string | null
  t_kind: string | null
}
const defaultSearchForm: SearchForm = {
  t_uid: null,
  t_title: null,
  t_kind: null
}
const searchForm: Ref<SearchForm> = ref({
  ...defaultSearchForm
})
const onSearch = async () => {
  const res = await topicGetTopicListService({
    t_title: searchForm.value.t_title,
    t_kind: searchForm.value.t_kind
  })
  data.value = res.data.data
  paginationReactive.page = 1
  //对数据的时间戳进行格式化
  data.value.forEach((item) => {
    item.create_time = formatTime(item.create_time)
  })
  message.success('搜索成功')
  console.log(searchForm.value)
}
//重置
const onReset = async () => {
  searchForm.value = { ...defaultSearchForm }
  paginationReactive.page = 1
  //恢复全部的数据
  const res = await topicGetTopicListService()
  data.value = res.data.data
  //对数据的时间戳进行格式化
  data.value.forEach((item) => {
    item.create_time = formatTime(item.create_time)
  })
  message.success('重置成功')
}
//处理删除
const handleDelete = async (id: number) => {
  await topicDeleteTopicService([id])
  //重新拉取的数据
  const res = await topicGetTopicListService()
  data.value = res.data.data
  //对数据的时间戳进行格式化
  data.value.forEach((item) => {
    item.create_time = formatTime(item.create_time)
  })
  message.success('删除成功')
  paginationReactive.page = 1
}
//处理批量删除
const checkedKeys: Ref<number[]> = ref<number[]>([])
//更新选中的行，返回选中的行的key，选择的行更新时触发
const onUpdateCheckedRowKeys = (keys: number[]) => {
  checkedKeys.value = keys
}
const handleBatchGenerationDelete = async () => {
  await topicDeleteTopicService(checkedKeys.value)
  //重新拉取的数据
  const res = await topicGetTopicListService()
  data.value = res.data.data
  //对数据的时间戳进行格式化
  data.value.forEach((item) => {
    item.create_time = formatTime(item.create_time)
  })
  message.success('删除成功')
  paginationReactive.page = 1
}
//提交修改
const commit = async (row: RowData) => {
  console.log(row)
  await topicChangeTopicService({
    id: row.id,
    t_kind: row.t_kind,
    recommend: row.recommend
  })
  //恢复全部的数据
  isLoading.value = true
  const res = await topicGetTopicListService()
  count.value = res.data.data.length
  data.value = res.data.data
  //对数据的时间戳进行格式化
  data.value.forEach((item) => {
    item.create_time = formatTime(item.create_time)
  })
  isLoading.value = false
  message.success('提交成功')
}
</script>
<template>
  <div class="flex justify-center flex-col gap-4">
    <NCard class="h-15 flex justify-center">
      <n-form class="flex flex-items-center" :model="searchForm">
        <NGrid :cols="24" x-gap="24">
          <n-form-item-gi span="6">
            <n-input-number placeholder="作者id" v-model:value="searchForm.t_uid"></n-input-number>
          </n-form-item-gi>
          <n-form-item-gi :span="6">
            <n-input placeholder="帖子名称" v-model:value="searchForm.t_title" />
          </n-form-item-gi>
          <n-form-item-gi :span="6">
            <n-input placeholder="帖子类别" v-model:value="searchForm.t_kind" />
          </n-form-item-gi>
          <n-form-item-gi :span="2" :offset="2">
            <n-button type="info" strong secondary size="medium" icon-placement="left" @click="onSearch">
              <template #icon>
                <n-icon>
                  <SearchOutline />
                </n-icon>
              </template>
              搜索
            </n-button>
          </n-form-item-gi>
          <n-form-item-gi :span="2">
            <n-button type="default" strong secondary size="medium" icon-placement="left" @click="onReset">
              <template #icon>
                <n-icon>
                  <Reset />
                </n-icon>
              </template>
              重置
            </n-button>
          </n-form-item-gi>
        </NGrid>
      </n-form>
    </NCard>
    <NCard>
      <div class="flex justify-between">
        <n-h4>共有数据：{{ count }} 条</n-h4>
        <n-space class="flex gap-4">
          <n-popconfirm @positive-click="handleBatchGenerationDelete" positive-text="确定" negative-text="取消">
            <template #trigger>
              <n-button type="error" size="small" ghost>
                <template #icon>
                  <n-icon>
                    <DeleteOutlined />
                  </n-icon>
                </template>
                批量删除
              </n-button>
            </template>
            你确定要删除吗？
          </n-popconfirm>
        </n-space>
      </div>
      <NDataTable
        :columns="columns"
        :data="data"
        :row-key="(row: RowData) => row.id"
        :max-height="320"
        :min-height="320"
        :scroll-x="1200"
        virtual-scroll
        :pagination="paginationReactive"
        size="small"
        :loading="isLoading"
        flex-height
        @update:checked-row-keys="onUpdateCheckedRowKeys"
      ></NDataTable>
    </NCard>
  </div>
</template>
